package com.qywx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qywx.dao.TagDao;
import com.qywx.dao.UserDao;
import com.qywx.entity.*;
import com.qywx.service.TagService;
import com.qywx.service.UserService;
import com.qywx.utils.R;
import com.qywx.utils.RestTemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @ClassName TagServiceImpl
 * @Description:
 * @Author wmj
 * @Date 2020/3/4
 * @Version V1.0
 **/
@Service("tagService")
public class TagServiceImpl implements TagService {

    private final static Logger log = LoggerFactory.getLogger(DepartmentServiceImpl.class);

    @Autowired
    TagDao tagDao;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    UserDao userDao;
    Logger logger = LoggerFactory.getLogger(TagServiceImpl.class);

    @Override
    @Transactional
    public R saveTag(TagEntity tagEntity) {
        String tagname = tagEntity.getTagname();
        if (tagname == null) {
            return R.error("请输入标签名称");
        }
        //判断标签是否存在
        TagEntity tag = tagDao.selectByName(tagname);
        if (tag != null) {
            return R.error("标签已存在");
        }
        //同步增加微信端
        //String accessToken = getAccessToken();
        String accessToken = restTemplateUtil.getaccessToken();
        if (accessToken != null) {
            //保存用户到企业微信
            String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token=" + accessToken;
            Map resultMap = restTemplateUtil.postRequest(url, tagEntity);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========保存标签到微信端返回信息===========" + errmsg, errmsg);
            if (0 == code) {
                Long tagid = ((Integer) resultMap.get("tagid")).longValue();
                tagEntity.setIsSynchronize("1");
                tagEntity.setTagid(tagid);
                tagDao.saveTag(tagEntity);
                //tagDao.updateById(tagEntity);
            } else {
                return R.error("保存标签到微信失败,请点击同步按钮再次进行同步");
            }
        } else {
            return R.error("获取access_token失败");
        }
        return R.ok();
    }

    @Override
    public R updateTag(TagEntity tagEntity) {
        tagDao.updateById(tagEntity);
        //同步更新微信端
        //String accessToken = getAccessToken();
        String accessToken = restTemplateUtil.getaccessToken();
        if (accessToken != null) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/update?access_token=" + accessToken;
            Map resultMap = restTemplateUtil.postRequest(url, tagEntity);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========更新微信端标签端返回信息===========" + errmsg, errmsg);
            if (0 != code) {
                tagEntity.setIsSynchronize("2");
                tagDao.updateById(tagEntity);
                return R.error("更新标签到微信失败,请点击同步按钮再次进行同步");
            }
        } else {
            return R.error("获取access_token失败");
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R delTag(Long tagid) {
        TagEntity tagEntity = tagDao.selectById(tagid);
        tagDao.backups(tagEntity);
        //删除标签
        tagDao.deleteById(tagid);
        //删除用户标签表中的标签
        tagDao.delTag(tagid);
        //同步删除微信端
        String accessToken = restTemplateUtil.getaccessToken();
        if (accessToken != null) {
            //同步删除标签
            String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/delete?access_token=" + accessToken + "&tagid=" + tagid;
            //发起请求
            Map resultMap = restTemplate.getForObject(url, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========删除微信端标签返回信息===========" + errmsg, errmsg);
            if (0 != code) {
                return R.error("微信端删除标签失败");
            }
        } else {
            return R.error("获取access_token失败");
        }
        return R.ok();
    }

    @Override
    public R getTagUser(Long tagid, int page, int size,int depid) {
        if (page < 1) {
            page = 1;
        }
        if (size < 1) {
            size = 10;
        }
        int start = (page - 1) * size;
        List<TagUserEntity> tagUserEntity;
        String total;
        if(0==depid){
            tagUserEntity = tagDao.getTagUser(tagid, start, size);
            //获取标签中用户得总数
            total = tagDao.getTotal(tagid);
        }else {
            tagUserEntity = tagDao.getTagDepidUser(tagid, start, size,depid);
            //获取标签中用户得总数
            total = tagDao.getTotaldepId(tagid,depid);

        }
        for (int i = 0; i < tagUserEntity.size(); i++) {
            TagUserEntity entity = tagUserEntity.get(i);
            //获取部门名称
            List<String> list = userDao.findByUserid(entity.getUserid());
            StringBuffer str = new StringBuffer();
            for (int j = 0; j < list.size(); j++) {
                str.append(list.get(j)).append("/");
            }
            String s = str.toString();
            if(!"".equals(s)&&null!=s){
                String depName = str.toString().substring(0,str.length()-1);
                entity.setDepName(depName);
            }
        }
        R r = new R();
        r.put("data", tagUserEntity);
        r.put("total", total);
        return r;
    }

    @Override
    @Transactional
    public R saveTagUser(Long tagid, String userids) {
        if (userids.contains(",")) {
            String[] userid = userids.split(",");
            for (int i = 0; i < userid.length; i++) {
                String userId = userid[i];
                UserTagEntity userTagEntity = tagDao.selByUseridAandTagid(userId, tagid);
                if (userTagEntity == null) {
                    tagDao.saveTagUser(tagid, userid[i]);
                }
            }
            //List<String> userIds = Arrays.asList(userid);
            //tagDao.batchInset(tagid,userIds);
        } else {
            UserTagEntity userTagEntity = tagDao.selByUseridAandTagid(userids, tagid);
            if (userTagEntity == null) {
                tagDao.saveTagUser(tagid, userids);
            }
        }
        //同步增加到微信
        //String accessToken = getAccessToken();
        String accessToken = restTemplateUtil.getaccessToken();
        if (accessToken != null) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("tagid", tagid);
            String[] userid = userids.split(",");
            List<String> list = Arrays.asList(userid);
            jsonObject.put("userlist", list);
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            //请求体
            HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
            //发起请求
            Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========保存标签用户到微信返回信息===========" + errmsg, errmsg);
            if (0 != code) {
                return R.error("保存标签用户到微信失败");
            }
        } else {
            return R.error("获取access_token失败");
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R saveTagDepartment(Long tagid, String departmentIds) {
        List<String> userids = new ArrayList<>();
        //根据部门di获取，所有人员id
        if (departmentIds.contains(",")) {
            String[] departmentId = departmentIds.split(",");
            for (int i = 0; i < departmentId.length; i++) {
                //String department = "," + departmentId[i] + ",";
                List<String> userid = userDao.findUserId(departmentIds);
                userids.addAll(userid);
            }
        } else {
            //获取部门下所有userid
            /*departmentIds = "," + departmentIds + ",";
            userids = userDao.findUserId(departmentIds);*/
            userids = userDao.findUserId(departmentIds);
        }
        if (userids != null && userids.size() > 0) {
            for (int i = 0; i < userids.size(); i++) {
                UserTagEntity userTagEntity = tagDao.selByUseridAandTagid(userids.get(i), tagid);
                if (userTagEntity == null) {
                    tagDao.saveTagUser(tagid, userids.get(i));
                }
            }
            //tagDao.batchInset(tagid, userids);
        }
        String accessToken = restTemplateUtil.getaccessToken();
        if (accessToken != null) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("tagid", tagid);
            if(userids.size()<1){
                return R.ok();
            }
            jsonObject.put("userlist", userids);
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            //请求体
            HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
            //发起请求
            Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========保存标签用户到微信返回信息===========" + errmsg, errmsg);
            if (0 != code) {
                return R.error("保存标签用户到微信失败");
            }
        } else {
            return R.error("获取access_token失败");
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R delTagUser(Long tagid, String userids) {
        if (userids.contains(",")) {
            String[] userid = userids.split(",");
            for (int i = 0; i < userid.length; i++) {
                tagDao.delTagUser(tagid, userid[i]);
            }
        } else {
            tagDao.delTagUser(tagid, userids);
        }
        //同步删除微信端
        //String accessToken = getAccessToken();
        String accessToken = restTemplateUtil.getaccessToken();
        if (accessToken != null) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/deltagusers?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("tagid", tagid);
            String[] userid = userids.split(",");
            List<String> list = Arrays.asList(userid);
            jsonObject.put("userlist", list);
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            //请求体
            HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
            //发起请求
            Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========删除微信端标签用户返回信息===========" + errmsg, errmsg);
            if (0 != code) {
                return R.error("删除微信端标签用户失败");
            }
        } else {
            return R.error("获取access_token失败");
        }
        return R.ok();
    }

    @Override
    public R geTagList() {
        List<TagEntity> tagEntityList = tagDao.geTagList();
        R r = new R();
        r.put("data", tagEntityList);
        return r;
    }

    @Override
    public R asynchronousDetection() {
        String count = tagDao.asynchronousDetection();
        return R.ok(count);
    }

    @Override
    public R synchronize() {
        List<TagEntity> tagEntityList = tagDao.synchronize();
        for (int i = 0; i < tagEntityList.size(); i++) {
            TagEntity tagEntity = tagEntityList.get(i);
            String isSynchronize = tagEntity.getIsSynchronize();
            String accessToken = restTemplateUtil.getaccessToken();
            if ("0".equals(isSynchronize)) {
                String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token=" + accessToken;
                Map resultMap = restTemplateUtil.postRequest(url, tagEntity);
                Integer code = (Integer) resultMap.get("errcode");
                String errmsg = (String) resultMap.get("errmsg");
                log.info("===========保存微信端标签用户返回信息===========" + errmsg, errmsg);
                if (0 == code) {
                    tagEntity.setIsSynchronize("1");
                    tagDao.updateById(tagEntity);
                } else {
                    return R.error("保存标签到微信失败");
                }
            } else {
                String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/update?access_token=" + accessToken;
                Map resultMap = restTemplateUtil.postRequest(url, tagEntity);
                Integer code = (Integer) resultMap.get("errcode");
                String errmsg = (String) resultMap.get("errmsg");
                log.info("===========更新微信端标签用户返回信息===========" + errmsg, errmsg);
                if (0 == code) {
                    tagEntity.setIsSynchronize("1");
                    tagDao.updateById(tagEntity);
                } else {
                    return R.error("更新标签到微信失败");
                }
            }
        }
        return R.ok();
    }

    @Override
    public List<ExportTagEntity> export(String tagid) {
        List<ExportTagEntity> exportTagEntityList = new ArrayList<ExportTagEntity>();
        if (tagid.contains(",")) {
            String[] tagId = tagid.split(",");
            for (int i = 0; i < tagId.length; i++) {
                //获取部门名称
                List<TagUserEntity> tagUserEntity = tagDao.getExportTag(tagId[i]);
                for (int j = 0; j < tagUserEntity.size(); j++) {
                    //获取部门名称
                    TagUserEntity entity = tagUserEntity.get(j);
                    String department = entity.getDepartment();
                    String depName = userServiceImpl.getDepNameById(department);
                    ExportTagEntity exportTagEntity = new ExportTagEntity();
                    exportTagEntity.setName(entity.getName());
                    exportTagEntity.setDepName(depName);
                    exportTagEntity.setTagname(entity.getTagname());
                    exportTagEntity.setType("成员");
                    exportTagEntity.setUserid(entity.getUserid());
                    exportTagEntity.setTagid(entity.getTagid());
                    exportTagEntityList.add(exportTagEntity);
                }
            }
        } else {
            //获取标签成员
            List<TagUserEntity> tagUserEntity = tagDao.getExportTag(tagid);
            for (int i = 0; i < tagUserEntity.size(); i++) {
                //获取部门名称
                TagUserEntity entity = tagUserEntity.get(i);
                String department = entity.getDepartment();
                String depName = userServiceImpl.getDepNameById(department);
                ExportTagEntity exportTagEntity = new ExportTagEntity();
                exportTagEntity.setName(entity.getName());
                exportTagEntity.setDepName(depName);
                exportTagEntity.setTagname(entity.getTagname());
                exportTagEntity.setType("成员");
                exportTagEntity.setUserid(entity.getUserid());
                exportTagEntity.setTagid(entity.getTagid());
                exportTagEntityList.add(exportTagEntity);
            }
        }
        return exportTagEntityList;
    }

    @Override
    @Transactional
    public R save(List<ExportTagEntity> list) {
        for (ExportTagEntity exportTagEntity : list) {
            UserTagEntity userTagEntity = new UserTagEntity();
            //判断用户是否存在
            String userid = exportTagEntity.getUserid();
            if (userid == null || "".equals(userid)) {
                return R.error("账号必填");
            }
            UserEntity userEntity = userDao.selectById(userid);
            if (userEntity == null) {
                return R.error(userid + "不存在");
            }
            userTagEntity.setUserids(exportTagEntity.getUserid());
            if (null == exportTagEntity.getTagname() || "".equals(exportTagEntity.getTagname())) {
                return R.error("标签必填");
            }
            Long tagId = tagDao.findTagIdByName(exportTagEntity.getTagname());
            if (tagId == null) {
                return R.error(exportTagEntity.getTagname() + "标签不存在");
            }
            userTagEntity.setTagid(tagId);
            tagDao.save(userTagEntity);
            String accessToken = restTemplateUtil.getaccessToken();
            if (accessToken != null) {
                String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token=" + accessToken;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("tagid", tagId);
                jsonObject.put("userlist", exportTagEntity.getUserid());
                //设置请求头
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                //请求体
                HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
                //发起请求
                Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
                Integer code = (Integer) resultMap.get("errcode");
                String errmsg = (String) resultMap.get("errmsg");
                log.info("===========保存标签用户到微信返回信息===========" + errmsg, errmsg);
                if (0 != code) {
                    return R.error("保存标签用户到微信失败");
                }
            } else {
                return R.error("获取access_token失败");
            }
        }
        return R.ok();
    }

    @Override
    public R findTagByName(String name) {
        List<TagEntity> tagEntityList = tagDao.findByName(name);
        R r = new R();
        r.put("data", tagEntityList);
        return r;
    }


}
